package com.sam.im.heiqun.uis.activities;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.sam.im.heiqun.R;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/1/24.
 */
public class ShowQRcodeActivity extends BaseSwipeBackActivity{

    @BindView(R.id.image_qr)
    ImageView image_qr ;
    @BindView(R.id.pre_v_back)
    ImageView pre_v_back ;
    @BindView(R.id.sure)
    Button sure ;

    String self_code_url = "";

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.weixin_qr_title);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        self_code_url = getIntent().getStringExtra("self_code_url");
        GlideUtils.loadImage(getApplicationContext(),self_code_url,image_qr);

    }

    @Override
    public int getContentViewId() {
        return R.layout.w_activity_show_qrcode;
    }

    @OnClick({R.id.pre_v_back,R.id.sure})
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
            case R.id.sure:
                image_qr.setDrawingCacheEnabled(true);
                Bitmap obmp = Bitmap.createBitmap(image_qr.getDrawingCache());
                image_qr.setDrawingCacheEnabled(false);

                try {
                    saveFile(obmp);
                } catch (IOException e) {
                    e.printStackTrace();
                    showToast(getResources().getString(R.string.weixin_qr_baocun_no));
                }

                break;
        }
    }

    public void saveFile(Bitmap bm)throws IOException {
        //Environment.getExternalStorageDirectory() ; 获得SDCard目录
        File dirFile = new File(Environment.getExternalStorageDirectory() + "/qrCodePay/");
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(Environment.getExternalStorageDirectory() + "/qrCodePay/" + "pay_code.png");
        //new FileOutputStream(myCaptureFile) 获取要保存到的文件的文件流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        //把指定的bitmp压缩到文件中 就是保存在指定文件中 format是文件格式（Bitmap.CompressFormat.JPEG jpeg）
        // quality 是品质（100 就是原质量）
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
        showToast(getResources().getString(R.string.weixin_qr_baocun_yes)+Environment.getExternalStorageDirectory() + "/qrCodePay/" + "pay_code.png");
    }

}
